package com.shopmall.product.service.Impl;

import com.alibaba.fastjson.JSON;
import com.shopmall.model.entity.product.Category;
import com.shopmall.product.mapper.CategoryMapper;
import com.shopmall.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<Category> selectOneCategory() {
        // 查询redis，是否有所有一级分类
        String categoryOneJson = redisTemplate.opsForValue().get("category:one");
        // redis含有一级分类，直接返回
        if (StringUtils.hasText(categoryOneJson)) {
            // categoryOneJson字符串转换成LiSt<Category>
            return JSON.parseArray(categoryOneJson, Category.class);
        }
        // 如果redis没有所有一级分类，查询数据库，并把查询内容加入redis
        List<Category> categoryList = categoryMapper.selectOneCategory();
        redisTemplate.opsForValue().set("category:one", JSON.toJSONString(categoryList), 7, TimeUnit.DAYS);
        return categoryList;
    }

    // 查询所有分类，树形封装
    @Cacheable(value = "category",key="'all'")
    @Override
    public List<Category> findCategoryTree() {
        // 查询所有分类，返回list集合
        List<Category> allCategoryList = categoryMapper.findAll();
        // 遍历所有分类list集合，通过条件parentId=0得到所有一级分类
        List<Category> oneCategoryList = allCategoryList
                .stream()
                .filter(item -> item.getParentId() == 0)
                .collect(Collectors.toList());
        // 遍历所有一级分类list集合，条件判断： id = parentId， 得到一级下面二级分类
        oneCategoryList.forEach(oneCategory -> {
            List<Category> twoCategoryList = allCategoryList
                    .stream()
                    .filter(item -> Objects.equals(item.getParentId(), oneCategory.getId()))
                    .collect(Collectors.toList());
            // 把二级分类封装到一级分类里面
            oneCategory.setChildren(twoCategoryList);
            // 遍历所有二级分类list集合，条件判断： id = parentId， 得到二级下面三级分类
            twoCategoryList.forEach(twoCategory -> {
                List<Category> threeCategoryList = allCategoryList.stream()
                        .filter(item -> Objects.equals(item.getParentId(), twoCategory.getId()))
                        .collect(Collectors.toList());
                // 把二级分类封装到一级分类里面
                twoCategory.setChildren(threeCategoryList);
            });
        });
        return oneCategoryList;
    }
}
